package com.mall.common.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mall.untils.PropertiesUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * 操作mongodb公共类
 * @author liudu
 *
 */
@SuppressWarnings("deprecation")
public class CopyOfMongoDBManagerback {
	
	private static Logger logger = LoggerFactory.getLogger(CopyOfMongoDBManagerback.class);
	private static Mongo mg = null;
	private static DB db = null;
	private final static CopyOfMongoDBManagerback mongoDbManager = new CopyOfMongoDBManagerback();

	/**
	 * 实例化
	 * 
	 * @return
	 * @throws Exception
	 */
	public static CopyOfMongoDBManagerback getInstance() throws Exception {
		return mongoDbManager;
	}

	static {
		try {
			mg = new Mongo(PropertiesUtil.getProperties("mongo.host"), Integer.parseInt(PropertiesUtil.getProperties("mongo.port")));
			db = mg.getDB(PropertiesUtil.getProperties("mongo.database.dail"));
		} catch (Exception e) {
			logger.error("Can't connect MongoDB!");
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * 获取集合（表）
	 * 
	 * @param collection
	 */
	public static DBCollection getCollection(String collection) {
		return db.getCollection(collection);
	}

	/**
	 * ----------------------------------分割线------------------------------------
	 * --
	 */
	/**
	 * 插入
	 * 
	 * @param collection
	 * @param map
	 */
	public static void insert(String collection, Map<String, Object> map) {
		try {
			DBObject dbObject = new BasicDBObject(map);
			getCollection(collection).insert(dbObject);
		} catch (MongoException e) {
			logger.error("MongoException:" + e.getMessage());
		}
	}

	/**
	 * 批量插入
	 * 
	 * @param collection
	 * @param list list类型为map
	 */
	public static void insertBatch(String collection, List<Map<String, Object>> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		try {
			List<DBObject> listDB = new ArrayList<DBObject>();
			for (int i = 0; i < list.size(); i++) {
				DBObject dbObject = new BasicDBObject(list.get(i));
				listDB.add(dbObject);
			}
			getCollection(collection).insert(listDB);
		} catch (MongoException e) {
			logger.error("MongoException:" + e.getMessage());
		}
	}

	/**
	 * 批量插入
	 * 
	 * @param collection
	 * @param list list类型为DBObject
	 */
	public static void insertBatchDBObject(String collection, List<DBObject> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		try {
			getCollection(collection).insert(list);
		} catch (MongoException e) {
			logger.error("MongoException:" + e.getMessage());
		}
	}
	
	/**
	 * 删除
	 * 
	 * @param collection
	 * @param map
	 */
	public static void delete(String collection, Map<String, Object> map) {
		DBObject obj = new BasicDBObject(map);
		getCollection(collection).remove(obj);
	}


	/**
	 * 批量删除
	 * 
	 * @param collection
	 * @param list
	 */
	public static void deleteBatch(String collection, List<Map<String, Object>> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			DBObject obj = new BasicDBObject(list.get(i));
			getCollection(collection).remove(obj);
		}
	}

	/**
	 * 计算满足条件条数
	 * 
	 * @param collection
	 * @param map
	 */
	public static long getCount(String collection, Map<String, Object> map) {
		BasicDBObject obj = new BasicDBObject(map);
		return getCollection(collection).getCount(obj);
	}

	/**
	 * 计算集合总条数
	 * 
	 * @param collection
	 * @param map
	 */
	public static long getCount(String collection) {
		return getCollection(collection).find().count();
	}

	/**
	 * 更新
	 * 
	 * @param collection
	 * @param setFields
	 * @param whereFields
	 */
	public static void update(String collection, Map<String, Object> setFields,
			Map<String, Object> whereFields) {
	    BasicDBObject q = new BasicDBObject(setFields);  
        BasicDBObject o = new BasicDBObject(whereFields);  
		getCollection(collection).update(q, o);
	}

	/**
	 * 查找对象（根据主键_id）
	 * 
	 * @param collection
	 * @param _id
	 */
	public static DBObject findById(String collection, String _id) {
		DBObject obj = new BasicDBObject();
//		obj.put("_id", ObjectId.massageToObjectId(_id));
		return getCollection(collection).findOne(obj);
	}

	/**
	 * 查找集合所有对象
	 * 
	 * @param collection
	 */
	public static List<DBObject> findAll(String collection) {
		return getCollection(collection).find().toArray();
	}

	/**
	 * 查找（返回一个对象）
	 * 
	 * @param map
	 * @param collection
	 */
	public static DBObject findOne(String collection, Map<String, Object> map) {
		DBCollection coll = getCollection(collection);
		return coll.findOne(new BasicDBObject(map));
	}

	/**
	 * 查找（返回一个List<DBObject>）
	 * 
	 * @param <DBObject>
	 * @param map
	 * @param collection
	 * @throws Exception
	 */
	public static List<DBObject> find(String collection, Map<String, Object> map) {
		DBCollection coll = getCollection(collection);
		DBCursor c = coll.find(new BasicDBObject(map));
		if (c != null)
			return c.toArray();
		else
			return null;
	}
	
	/**
	 * 根据时间(commit_time)查找（返回一个List<DBObject>）
	 * @param collection 表明
	 * @param dbo 查询条件
	 * @return
	 */
	public static List<DBObject> findForCommitTime(String collection, BasicDBObject dbo) {
		
		DBCollection coll = getCollection(collection);
		DBCursor c = coll.find(dbo).addOption(Bytes.QUERYOPTION_NOTIMEOUT);//设置不超时查询
		if (c != null){
			return c.toArray();
		}
		return null;
	}
}
